/**
 * Copyright (c) 2011-2014, hubin (243194995@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.sakz.oss;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;



/**
 * <p>
 * 
 * @author hunter
 * @date 2017年12月21日
 * @version 1.0.0
 */
@Controller
public class LoginController {

	protected static Logger logger=LoggerFactory.getLogger(LoginController.class);  

    @RequestMapping(value = "/sso", method = {RequestMethod.GET,RequestMethod.POST})  
    public void sso(String service,HttpServletRequest request,HttpServletResponse response) throws Exception {
    	Cookie[] cookies = request.getCookies(); 
    	if(cookies!=null) {
    	   	   for (int i = 0; i < cookies.length; i++) {
    	   		    logger.debug(service+"=>"+cookies[i].getName()+","+cookies[i].getValue());
    	            if ("token".equals(cookies[i].getName())) {//如果token存在，则表明在其他系统上登录过，则带上token直接重定向至目标页面
    	            	logger.info("redirect service url=>"+service);
    	            	response.sendRedirect(service+"?token="+cookies[i].getValue());
    	            	return;
    	             } 
    	        }
    	}
   	    logger.info("forward sso login  ui url");//转发至登录页面
   	    request.setAttribute("service", service);
   	    request.getRequestDispatcher("login").forward(request, response);
    }
    
	
	
	/**
	 * 单点登录的页面
	 * @param backurl
	 * @return
	 * @throws  
	 * @throws Exception 
	 */
    @RequestMapping(value = "/login", method = {RequestMethod.GET,RequestMethod.POST})  
    public String login() throws Exception {
    	return "login";
    }
    
    /**
     * 单点登陆的token获取入口
     * @param backurl
     * @param username
     * @param password
     * @param response
     * @return
     */
    @RequestMapping(value = "/token", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String token(String backurl,String username,String password,HttpServletResponse response) {
    	logger.info("SSO LOGIN USERNAME=>"+username);
    	if(!"admin".equals(username)) {
    		return "-1";
    	}
    	String  token=UUID.randomUUID().toString();
    	
    	User u=new User();
    	
    	UserSSOInfo info=new UserSSOInfo();
    	info.setUserId(username);
    	info.setUserInfo(u);
    	
    	u.setSex("男-女");
    	u.setUserName(username);
    	
    	
    	
    	TokenManager.getInstance().add(token, info);
    	/**
    	 * 设置响应cookie  带回token 置于浏览器端
    	 */
    	Cookie cookie = new Cookie("token", token); 
        //设置生命周期以秒为单位 
//        cookie.setMaxAge(6000); 
//    	cookie.setHttpOnly(true);
    	cookie.setDomain("www.sso.com");
    	response.addCookie(cookie);
    	logger.info("SSO LOGIN SUCC USERNAME TOKEN=>"+token);
    	return token;
    }
    
    @RequestMapping(value = "/status", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String status(HttpServletRequest request) {
    	 Cookie[] cookies = request.getCookies();
    	 if(cookies!=null) {
        	 for (int i = 0; i < cookies.length; i++) {
        		 logger.info(cookies[i].getName()+","+cookies[i].getValue());
                 if ("token".equals(cookies[i].getName())) { 
                	 return TokenManager.getInstance().get(cookies[i].getValue()).toString();
                  } 
             } 
    	 }

    	return "该用户尚未登录";
    }
    
    @RequestMapping(value = "/verfiy", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public AuthenticatorRlt verfiy(HttpServletRequest request,String token) throws JsonProcessingException {
    	 logger.info("正在发起认证:"+token);//转发至登录页面
    	 AuthenticatorRlt rlt=new AuthenticatorRlt();
    	UserSSOInfo userSSOInfo=TokenManager.getInstance().get(token);
    	if(userSSOInfo!=null) {
    		logger.info("认证完成，用户信息"+userSSOInfo.getUserInfo());//转发至登录页面
    		rlt.setUserId(userSSOInfo.getUserId());
    		rlt.setUserInfo(new ObjectMapper().writeValueAsString(userSSOInfo.getUserInfo()));
    		rlt.setVaild(true);
    		return rlt;
    	}
    	return null;
    }
}